<template>
  <div>
    <div class="content">
      <el-tabs type="border-card" v-model="activeName">
        <el-tab-pane :label="item.name" :name="item.field" v-for="item in moduleConfig" :key="item.field" v-if="item.visible">
          <table v-if="item.field == 'info'" class="el-table">
            <tbody>
              <tr v-for="i in projectConfig" :key="i.field">
                <td class="first-col">{{i.name}}</td>
                <td>{{projectData[i.field]}}</td>
              </tr>
            </tbody>
          </table>
          <div v-if="item.field == 'pic'">
            <div style="text-align: center" v-if="!defaultTopoContent">
              <p style="line-height: 50px;font-size: 20px;">当前没有创建画面或没有默认画面!<br>请在设置>画面中进行创建和设置!</p>
            </div>
            <div id="graph" v-else></div>
          </div>
          <div v-if="item.field == 'data'">
            <dataitemlist :device-id="gateways && gateways.join(',')" type="project" @show-history-data="showHistoryData" v-if="!showItemData"></dataitemlist>
            <itemdata v-if="showItemData" :device-id="itemData.deviceId" :item-id="itemData.itemId" :item-name="itemData.itemName"></itemdata>
          </div>
          <div v-if="item.field == 'trend'">
            <el-card class="box-card">
              <p>提示</p><br>
              <p>1.选择要绘制曲线的开始时间和结束时间</p>
              <p>2.选择每条曲线对应的数据项</p>
            </el-card>
            <el-card class="box-card" style="margin: 20px 0">
              <el-form label-position="right" label-width="100px" :model="formTrendData">
                <el-form-item label="趋势图名称">
                  <el-input v-model="formTrendData.name"></el-input>
                </el-form-item>
                <el-form-item label="起止时间">
                  <el-col :span="11">
                    <el-date-picker type="date" placeholder="开始时间" v-model="formTrendData.startdate" style="width: 100%;"></el-date-picker>
                  </el-col>
                  <el-col class="line" :span="2">-</el-col>
                  <el-col :span="11">
                    <el-date-picker type="date" placeholder="结束时间" v-model="formTrendData.enddate" style="width: 100%;"></el-date-picker>
                  </el-col>
                </el-form-item>
                <el-form-item label="数据项">
                  <el-select v-model="formTrendData.dataitem" placeholder="请选择" style="width: 100%;" :loading="loading">
                    <el-option-group
                      v-for="group in dataitem"
                      :key="group.label"
                      :label="group.label">
                      <el-option
                        v-for="item in group.options"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                      </el-option>
                    </el-option-group>
                  </el-select>
                </el-form-item>
              </el-form>
              <el-button type="primary" @click="renderChart">绘制曲线</el-button>
            </el-card>
            <div class="chart-container">
              <echarts :option="chartOption"></echarts>
            </div>
          </div>
          <el-row :gutter="20" v-if="item.field == 'setting'">
            <el-col :span="4">
              <el-menu default-active="info" class="el-menu-vertical-demo" @select="handleSelect">
                <el-menu-item index="info">信息</el-menu-item>
                <el-menu-item index="module">模块</el-menu-item>
                <el-menu-item index="gateway">网关</el-menu-item>
                <el-menu-item index="pic">画面</el-menu-item>
              </el-menu>
            </el-col>
            <el-col :span="20">
              <table v-if="currentSetting == 'info'" class="el-table">
                <tbody>
                  <tr v-for="i in projectConfig" :key="i.field">
                    <td class="first-col">{{i.name}}</td>
                    <td><input type="" name="" v-model="projectData[i.field]"></td>
                  </tr>
                  <tr class="save-project-tr">
                    <td></td>
                    <td class="save-project-td">
                      <el-button type="primary" @click="save">保存</el-button>
                      <el-button @click="cancel">取消</el-button>
                    </td>
                  </tr>
                </tbody>
              </table>
              <div v-if="currentSetting == 'module'" class="common-setting">
                <modulesetting @save-module-setting="settingModuleInfo" :config="moduleData"></modulesetting>
              </div>
              <div v-if="currentSetting == 'gateway'" class="common-setting">
                <devicelist @save-device-setting="settingGatewayInfo" :project-id="projectId" :info="projectData"></devicelist>
              </div>
              <div v-if="currentSetting == 'pic'" class="common-setting">
                <topo :project-id="projectId"></topo>
              </div>
            </el-col>
          </el-row>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>
<script>
import _ from 'lodash'
import moment from 'moment'
import utils from '../../utils/dict'
import modulesetting from './../common/modulesetting'
import devicelist from './../common/devicelist'
import topo from './../common/topo'
import echarts from '../common/echarts'
import dataitemlist from './../common/dataitemlist'
import itemdata from './../common/itemdata'

// 项目信息列名
const projectFields = [ 'name', 'projectType', 'province', 'city', 'employer', 'customType', 'address', 'latitude', 'longitude', 'purchaseDate', 'installationDate', 'contactName', 'contactPhone' ]
// const moduleFields = ['info', 'pic', 'data', 'alert', 'trend']
const moduleFields = ['info', 'pic', 'data', 'trend']
const DATE_FORMAT = 'YYYY-MM-DD HH:mm:ss'

export default {
  name: 'project-detail',
  data () {
    return {
      moduleFields: moduleFields,
      moduleConfig: null,
      moduleData: null,
      tableData: [{
        date: '项目名称',
        name: '王小虎'
      }],
      tableData2: [{
        date: '项目名称',
        name: '王小虎'
      }],
      projectId: null,
      projectFields: projectFields,
      projectConfig: null,
      projectData: null,
      cloneProjectData: null,
      currentSetting: 'info',
      gateways: null,
      formTrendData: {
        name: '',
        startdate: '',
        enddate: '',
        dataitem: ''
      },
      activeName: 'info',
      loading: false,
      dataitem: null,
      chartOption: {},
      showItemData: false,
      itemData: null,
      defaultTopoContent: null,
      defaultTopoShowTimes: 0
    }
  },
  watch: {
    moduleConfig () {
      if (this.moduleConfig && this.moduleConfig.length) {
        this.activeName = this.moduleConfig[0].field
      }
    },
    activeName () {
      if (this.activeName === 'trend') {
        this.getDataItem()
      }
      if (this.activeName === 'data') {
        this.showItemData = false
      }
      if (this.activeName === 'pic') {
        this.requestTopo()
      }
    }
  },
  components: {
    modulesetting,
    devicelist,
    topo,
    echarts,
    dataitemlist,
    itemdata
  },
  mounted () {
    this.projectId = this.$route.params.id
    this.requestModuleConfig()
    this.requestProjectInfo()
  },
  methods: {
    show () {
      this.defaultTopoShowTimes++
      if (this.defaultTopoShowTimes > 1) {
        return
      }
      setTimeout(() => {
        var graph = new window.Graph(document.getElementById('graph'))
        graph.resizeContainer = true
        graph.setEnabled(false)
        var xmlDoc = window.mxUtils.parseXml(this.defaultTopoContent)
        /* eslint-disable new-cap */
        var codec = new window.mxCodec(xmlDoc)
        codec.decode(xmlDoc.documentElement, graph.getModel())
      }, 0)
    },
    requestModuleConfig () {
      // 模块配置请求
      this.$http.get('/project/module/find?project_id=' + this.projectId).then((res) => {
        this.buildModuleData(res.data)
      })
    },
    buildModuleData (data) {
      this.moduleData = data
      this.moduleConfig = _.map(this.moduleFields, (item) => {
        return {
          field: item,
          name: utils.moduleSetting[item] || item,
          visible: !!data[item]
        }
      })
      this.moduleConfig.push({
        field: 'setting',
        name: '设置',
        visible: true
      })
    },
    requestProjectInfo () {
      // 项目信息请求
      this.$http.get('/project/find?id=' + this.projectId).then((res) => {
        this.projectData = res.data
        this.cloneProjectData = _.clone(this.projectData)
        this.gateways = this.projectData.gateways
        this.projectConfig = _.map(this.projectFields, (item) => {
          return {
            field: item,
            name: utils.projectFieldDict[item] || item,
            value: res.data[item] ? res.data[item] : ''
          }
        })
      })
    },
    requestTopo () {
      this.$http.get('/project/configuration/find?project_id=' + this.projectId).then((res) => {
        var defaultTopo = _.filter(res.data, (item) => {
          return item.defaultValue
        })
        if (defaultTopo.length && defaultTopo[0].content) {
          this.defaultTopoContent = defaultTopo[0].content
        }
        if (this.defaultTopoContent) {
          this.show()
        }
      })
    },
    handleSelect (key, keyPath) {
      this.currentSetting = key
    },
    getDataItem () {
      if (this.projectData &&
        this.projectData.gateways &&
        this.projectData.gateways.length) {
        var allDeviceRequest = _.map(this.projectData.gateways, (gateway) => {
          return this.$http.get('/data/current?device_id=' + gateway)
        })
        Promise.all(allDeviceRequest).then((allData) => {
          this.dataitem = _.map(allData, (data, index) => {
            var ret = _.map(data.data.currentDataList, (item) => {
              return {
                // value: item.devid + '--' + item.itemid,
                value: this.projectData.gateways[index] + '--' + item.itemid,
                label: item.itemname
              }
            })
            return {
              label: this.projectData.gateways[index],
              options: ret
            }
          })
        })
      } else {
        this.$message({
          message: '请先绑定网关',
          type: 'warning'
        })
      }
    },
    showHistoryData (data) {
      this.itemData = data
      this.showItemData = true
    },
    renderChart () {
      if (!this.formTrendData.startdate ||
        !this.formTrendData.enddate ||
        !this.formTrendData.dataitem) {
        this.$message({
          message: '有必填项未填！',
          type: 'warning'
        })
        return
      }
      var startdate = this.getTime(this.formTrendData.startdate)
      var enddate = this.getTime(this.formTrendData.enddate)
      var deviceId = this.formTrendData.dataitem.split('--')[0]
      var dataitemId = this.formTrendData.dataitem.split('--')[1]
      this.$http.get('/data/history/dataitem/?device_id=' + deviceId + '&dataitem_id=' + dataitemId + '&start_time=' + startdate + '&end_time=' + enddate).then((res) => {
        var seriesData = _.chain(res.data.historyDataList).map((item) => {
          return {
            name: moment(item.htime).format(DATE_FORMAT),
            value: item.val
          }
        }).sortBy('name').value()
        this.chartOption = {
          title: {
            text: this.formTrendData.name || '图例'
          },
          tooltip: {
            trigger: 'axis'
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: {
            type: 'category'
          },
          yAxis: {
            type: 'value'
          },
          series: [{
            name: '数值',
            type: 'line',
            data: seriesData
          }]
        }
      })
    },
    getTime (date) {
      return moment(date).toDate().getTime()
    },
    settingModuleInfo (data) {
      // 更新项目的权限
      delete data.createTime
      delete data.updateTime
      // todo： 接口报错
      this.$http.post('/project/module/update', data).then((res) => {
        this.$message({
          message: '成功',
          type: 'success'
        })
      })
    },
    settingGatewayInfo (data) {
      // 保存网关信息
      this.gateways = _.map(data, (item) => {
        return item.deviceId
      })
      this.projectData.gateways = this.gateways
      this.save()
    },
    save () {
      // 保存
      this.$http.post('/project/create', this.projectData).then((res) => {
        this.updateData(res.data)
        this.$message({
          message: '保存成功',
          type: 'success'
        })
      })
    },
    cancel () {
      // 取消
      this.resetEditData()
      this.$message({
        message: '取消修改成功',
        type: 'success'
      })
    },
    updateData (data) {
      this.projectData = data
      this.cloneProjectData = _.clone(this.projectData)
    },
    resetEditData () {
      this.projectData = _.clone(this.cloneProjectData)
    }
  }
}
</script>
<style lang="stylus" scoped>
.content {
  padding: 20px;
}
.first-col {
  text-align: right;
  width: 30%;
}
.el-table .info-row {
  background: #c9e5f5;
}

.el-table .positive-row {
  background: #e2f0e4;
}
.el-table tr td {
  padding: 0 30px;
}
.el-table td {
  border-right: 1px solid #dfe6ec;
  border-bottom: 1px solid #dfe6ec;
}
.save-project-tr {
  td {
    border: none;
  }
  td.save-project-td {
    padding-left: 0;
  }
  .el-button {
    margin: 15px 10px 15px 0px;
  }
}
.el-col-20 {
  font-size: 14px;
  .common-setting {
    border:1px solid #dfe6ec;
    padding:20px;
  }
}
.line {
  text-align: center;
}

</style>
